package com.AAA.controller.mht;

import com.AAA.Util.EasyExcelUtil;
import com.AAA.entity.LayData;
import com.AAA.entity.MyPage;
import com.AAA.entity.mht.TMht;
import com.AAA.service.Impl.mht.TmhtRecordDedtailServiceImpl;
import com.AAA.service.Impl.mht.TmhtServiceImpl;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("tmht")
public class TmhtController {

    @Autowired
    private TmhtServiceImpl service;
    @Autowired
    private TmhtRecordDedtailServiceImpl dedtailService;
    @PostMapping("addall")
    @ResponseBody
public LayData addAll(HttpServletRequest request, Model model, MultipartFile file) throws IOException {

        List<Object> objects = EasyExcelUtil.readExcel(file, new TMht(), 1, 1);
        int count=0;
        List<Integer> list=new ArrayList<>();
        LayData layData=new LayData();
        for (Object t:objects){
            TMht tMht= (TMht) t;
            count++;

            boolean addall = service.addall(tMht);
            if (!addall){
                list.add(count);
            }
        }
        if (list.size()==0){
            layData.setMsg("添加成功");
        }else {
            layData.setData("有第"+list.toString()+"条未添加成功");
        }
        return layData;
    }

    @RequestMapping("queryall")
    @ResponseBody
    public LayData queryall(MyPage myPage,TMht tMht){
        PageInfo pageInfo=service.query(myPage,tMht);
        return new LayData(pageInfo);
    }

    @PostMapping("add")
    @ResponseBody
        public LayData add(TMht tMht){

        if(tMht.getQid()==null){
            return new LayData(service.add(tMht));
        }else{
            return new LayData(service.edit(tMht));
        }

}

@PostMapping("del")
@ResponseBody
    public LayData delete(Integer qid){
    TMht tMht = service.selectById(qid);
    Integer tid = tMht.getTid();
    boolean b = dedtailService.selectByTid(tid);
    if(b){
       return new LayData(0);
        }else {
        boolean delete = service.delete(qid);
        return new LayData(delete );
    }

}

    @GetMapping("index")
    public String getIndexAllSub(MyPage myPage, HttpServletRequest request){
        myPage.setLimit(100);
        myPage.setPage(1);
        PageInfo all = service.query(myPage,new TMht());
        request.setAttribute("allsub",all);

        return "view/mhttest";

    }
}
